<?php

class topic_helper
{
    /**
     * 获取任务列表, ID索引
     *
     * @return multitype
     * @throws AnException
     */
    public static function get_job_list() {
        return api_helper::array_to_filelds_assoc('id', _model('topic_job')->getList(array(1 => 1)));
    }

    /**
     * 获取第一个任务
     *
     * @return int
     * @throws AnException
     */
    public static function get_default_job_id() {
        $info = _model('topic_job')->read(array(1 => 1));
        if ($info) {
            return $info['id'];
        } else {
            return 0;
        }
    }

    /**
     * 获取激活的任务列表
     *
     * @return array
     * @throws AnException
     */
    public static function get_actived_job_num($term = array()) {
        return count(self::get_actived_job_list($term));
    }

    /**
     * 获取激活的任务列表
     *
     * @return array
     * @throws AnException
     */
    public static function get_actived_job_list($term = array()) {
        $today = date('Y-m-d');
        $filter = array();

        $filter['start_date <= '] = $today;
        $filter['end_date >= '] = $today;

        $list = _model('topic_job')->getList($filter);
        $job_list = array();
        if (!empty($list)) {
            foreach ($list as $k => $job) {
                $term_config = json_decode($job['term'], true);
                // 白名单限制
                if (!empty($term_config['agency_ids']) &&
                    isset($term['agency_id']) &&
                    !in_array((string)$term['agency_id'], $term_config['agency_ids'])
                ) {
                    continue;
                }
                // TODO 未来其他白名单

                $job_list[] = parse_param(array(
                    'id' => '',
                    'name' => '',
                    'start_date' => '',
                    'end_date' => '',
                    'info' => '',
                    'remaining' => ceil((strtotime($job['end_date']) - time()) / 86400)
                ), $job);
            }
        }

        return $job_list;
    }

    /**
     * 根据id获取任务名称
     *
     * @param int $id
     * @return bool
     * @throws AnException
     */
    public static function get_job_name_by_id($id = 0) {
        if ($id == 0) {
            return false;
        }
        $ret = _model('topic_job')->getFields('name', array('id' => $id));

        return empty($ret) ? false : $ret[0];
    }
}